package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pic-text-manager/cache"
	"pic-text-manager/model"
	"strconv"
	"time"
)

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var article model.Article
	redis_key := "detail" + strconv.Itoa(id)
	cachaData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cachaData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachaData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var article []model.Article
	var total int64
	redis_key := "list_" + strconv.Itoa(page)
	cachaData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cachaData == "" {
		model.DB.Offset(offset).Limit(size).Order("id DESC").Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachaData), &article)
	}
	model.DB.Model(&article).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  article,
		"total": total,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	content := c.PostForm("content")
	if title == "" || author == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "发布失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	data := model.Article{
		Title:   title,
		Author:  author,
		Content: content,
	}
	err := tx.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	var article model.Article
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	tx.Where("id=?", data.ID).Find(&article)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	err = tx.Commit().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}
